<template>
  <div>
    <el-drawer
      title="我是标题"
      :visible.sync="drawer"
      :with-header="false"
      size="800px"
      :wrapper-closable="false"
    >
      <!-- 头部 -->
      <div class="newly">
        <span @click="drawergb">X</span>
        <span>{{ text }}</span>
      </div>
      <template>
        <el-form ref="form" :rules="rules" :model="formData" style="margin: 0 10px 0 30px;min-height:800px">
          <el-tabs v-model="activeName">
            <!-- 基础信息 -->
            <el-tab-pane label="基础信息" name="first">
              <!-- 所属小区 / 投票标题 -->
              <el-row type="flex">
                <el-form-item label="所属小区" size="small" prop="community_code" style="margin-right: 23px;">
                  <el-select v-model="formData.community_code" style="margin-right: 0px;width:328px;margin-top: 13px" placeholder="请输入">
                    <el-option v-for="item in community" :key="item.id" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
                <el-form-item label="投票标题" prop="title">
                  <el-input v-model="formData.title" size="small" style="width:328px" />
                </el-form-item>
              </el-row>
              <!-- 开始时间 / 结束时间 -->
              <el-row type="flex">
                <el-form-item label="开始时间" size="small" prop="start_time" style="margin-right: 23px;">
                  <div class="block">

                    <el-date-picker
                      v-model="formData.start_time"
                      style="width:328px"
                      type="datetime"
                      placeholder="选择日期时间"
                    />
                  </div>
                </el-form-item>
                <el-form-item label="结束时间" size="small" prop="end_time">
                  <div class="block">
                    <el-date-picker
                      v-model="formData.end_time"
                      style="width:328px"
                      type="datetime"
                      placeholder="选择日期时间"
                    />
                  </div>
                </el-form-item>
              </el-row>
              <!-- 是否支持多选 / 是否匿名 -->
              <el-row type="flex">
                <div style="width:353px">
                  <el-form-item label="是否支持多选" prop="multi">
                    <template style="width:328px">
                      <el-radio-group v-model="formData.multi">
                        <el-radio :label="0">不支持</el-radio>
                        <el-radio :label="1">支持</el-radio>
                      </el-radio-group>
                    </template>
                  </el-form-item>
                </div>
                <el-form-item label="是否匿名" prop="anonymous">
                  <template style="width:328px">
                    <el-radio-group v-model="formData.anonymous">
                      <el-radio :label="0">匿名</el-radio>
                      <el-radio :label="1">不匿名</el-radio>
                    </el-radio-group>
                  </template>
                </el-form-item>
              </el-row>

              <!-- 状态 -->

              <el-form-item label="状态" prop="status">
                <template slot-scope="">
                  <el-radio-group v-model="formData.status">
                    <el-radio :label="0">关闭</el-radio>
                    <el-radio :label="1">启用</el-radio>
                  </el-radio-group>
                </template>
              </el-form-item>

            </el-tab-pane>
            <!-- 选项信息 -->

            <el-tab-pane label="选项信息" name="second">

              <el-table
                :data="formData.options"
                :header-cell-style="{background:'#fafafa'}"
                style="width: 100%"
              >
                <div slot="empty" style="color:#dedede;">

                  <span class="el-icon-folder-opened" style="font-size: 32px;" />
                  暂无数据

                </div>
                <!-- 选项名称 -->
                <el-table-column
                  prop="name"
                  label="选项名称"
                  width="112"
                >
                  <template slot-scope="{row}">
                    <el-form-item>
                      <el-input v-model="row.name" size="small" placeholder="请输入" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- 选项描述 -->
                <el-table-column
                  prop="prop"
                  label="选项描述"
                  width="300"
                >
                  <template slot-scope="{row}">
                    <el-form-item>
                      <el-input
                        v-model="row.description"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入内容"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- 图片地址 -->
                <el-table-column
                  prop="prop"
                  label="图片地址"
                  width="170"
                >
                  <template slot-scope="{row}">
                    <el-form-item>
                      <el-upload
                        v-model="row.img_url"
                        class="updispck"
                        action="#"
                        :limit="row.limit"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :before-upload="beforeupload"
                        :on-success="onSuccessFile"
                        :on-change="function( file){return handleChange(file, row.kd)}"
                        :on-remove="function( file){return handleRemove(row.kd)}"
                        :file-list="row.img"
                        :class="{disabled: row.img.length === row.limit}"
                      >

                        <i class="el-icon-plus" />
                      </el-upload>
                      <!-- <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
                        <img width="100%" src="../../../../../../微信图片_20230307145902.png" alt="">
                      </el-dialog> -->
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- 操作 -->
                <el-table-column
                  prop="prop"
                  label="操作"
                  width="170"
                >
                  <template slot-scope="{row}">
                    <div style="color:#63b0ff" @click="delArray(row.kd)">删除</div>
                  </template>
                </el-table-column>
              </el-table>

              <div class="box" @click="addArray">+ 新增选项</div>

            </el-tab-pane>

            <!-- 详细信息 -->
            <el-tab-pane label="详细信息" name="third">
              <el-row type="flex">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="formData.remark" type="textarea" :rows="3" style="width:328px" />
                </el-form-item>
                <!-- 图片 -->
                <el-form-item prop="img_url" label="封面图片" style="margin-left: 10px;width:528px">
                  <div />
                  <!-- limit控制上传图片数量 -->
                  <el-upload
                    v-model="formData.img_url"
                    class="updispck"
                    action="#"
                    :limit="limit"
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :before-upload="beforeupload"
                    :http-request="httpRequest"
                    :on-success="onSuccess"
                    :on-remove="onRemove"
                    :file-list="fileList"
                    :class="{disabled: fileList.length === limit}"
                  >
                    <i class="el-icon-plus" />
                  </el-upload>
                  <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
                    <img width="100%" :src="dialogImageUrl" alt="">
                  </el-dialog>
                </el-form-item>
              </el-row>
              <!-- 编辑器 -->
              <el-form-item label="内容" prop="description">
                <template>
                  <div style="border: 1px solid #ccc;margin-top:50px;">
                    <Toolbar
                      style="border-bottom: 1px solid #ccc;"
                      :editor="editor"
                    />
                    <Editor
                      v-model="formData.description"
                      style="height: 300px; overflow-y: hidden;"
                      @onCreated="onCreated"
                    />
                  </div>
                </template>
              </el-form-item>
            </el-tab-pane>

          </el-tabs>
        </el-form>
      </template>
      <!-- 确定 / 取消 -->
      <div class="newly" style="border-bottom:none;border-top:1px solid red">
        <el-row type="flex" justify="end" style="margin-top: 20px;">
          <el-button
            type="primary"
            size="small"
            @click="onSubmit(formData.id)"
          >提交</el-button>
          <el-button size="small" @click="drawergb">关闭</el-button>
        </el-row>
      </div>

    </el-drawer>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getImgApi } from '@/api/auth-user'
import { getIedireApi, getPutApi } from '@/api/ticket'
export default {
  name: 'Popup',
  components: { Editor, Toolbar },
  props: {
    community: {
      type: Array,
      default: () => {}
    }
  },
  data() {
    return {
      index: 0,
      editor: null,
      dialogImageUrl: '',
      dialogVisible: false,
      file: [],
      fileList: [],
      // 暂存区
      //   staging: '',
      // 上传开关
      showPercent: false,
      drawer: false, // 控制抽屉
      text: '',
      activeName: 'first',
      limit: 3, // 控制上传图片数量
      limitFile: 1, // 控制上传图片数量
      formData: {
        description: '', // 编辑器内容
        options: [], // 选项个数
        img_url: '', // 封面图片
        anonymous: 1, // 匿名
        community_code: '', // 所属小区code
        end_time: '', // 结束时间
        start_time: '', // 开始时间
        multi: 1, // 是否支持
        remark: '', // 备注
        status: 1, // 状态
        title: ''// 投票标题

      },
      // 表单验证规则
      rules: {
        description: [{ required: true, message: '请输入', trigger: 'input' }],
        optionsimg_url: [{ required: true, message: '请输入', trigger: 'blur' }],
        img_url: [{ required: true, message: '请输入', trigger: 'blur' }],
        anonymous: [{ required: true, message: '请输入', trigger: 'change' }],
        community_code: [{ required: true, message: '请输入', trigger: 'change' }],
        end_time: [{ required: true, message: '请输入', trigger: 'blur' }],
        start_time: [{ required: true, message: '请输入', trigger: 'blur' }],
        multi: [{ required: true, message: '请输入', trigger: 'change' }],
        remark: [{ required: true, message: '请输入', trigger: 'blur' }],
        status: [{ required: true, message: '请输入', trigger: 'change' }],
        title: [{ required: true, message: '请输入', trigger: 'blur' }],
        optionsdescription: [{ required: true, message: '请输入', trigger: 'blur' }],
        optionsname: [{ required: true, message: '请输入', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 选项自定义上传头像
    async  handleChange(file, index) {
      console.log(index, file)
      const fd = new FormData()
      fd.append('file', file.raw)
      const res = await getImgApi(fd)
      this.formData.options[index].img = [{ url: `http://124.223.14.236:8881${res.data.data.url}` }]
      this.formData.options[index].img_url = res.data.data.url
    },
    // 删除选项options
    delArray(index) {
      // 点击的时候遍历options，把不满足条件的返回新数组赋值给options，这样就可以点击删除啦
      this.formData.options = this.formData.options.filter(item => item.kd !== index)
      this.formData.options.forEach((item, index) => {
        if (item.kd > index) {
          this.formData.options[index].kd = item.kd - 1
        }
      })
    },
    // 提交 修改 / 编辑
    async onSubmit(id) {
      await this.$refs.form.validate()
      // 把时间处理成时间戳上传
      // 接口返回的是时间戳，但是自己选择时间就会变成标准时间，所以判断转一下
      // 字符串截取判断，如果是时间的话，第25位是G
      if (this.formData.end_time.toString().substring(25, 26) === 'G') { this.formData.end_time = Date.parse(this.formData.end_time) }
      if (this.formData.start_time.toString().substring(25, 26) === 'G') { this.formData.start_time = Date.parse(this.formData.start_time) }
      if (id) {
        // 编辑
        // 将数组转为字符串
        if (this.formData.img_url instanceof Array) {
          // 提交之前把图片处理成字符串
          this.formData.img_url = this.formData.img_url.toString()
        }
        await getPutApi({ ...this.formData })
        // 调用父级刷新页面
        this.$parent.gettableData()
        // 关闭框
        this.drawergb()
        this.$message.success('修改成功')
      } else {
        // 新增
        await getIedireApi(this.formData)
        // 调用父级刷新页面
        this.$parent.gettableData()
        this.$message.success('添加成功')
        // 关闭框
        this.drawergb()
      }
    },

    // 关闭弹框
    drawergb() {
      this.drawer = false
      this.$refs.form.clearValidate()
      this.file = []
      this.fileList = []
      this.activeName = 'first'
      // 清空
      this.formData = {
        description: '', // 编辑器内容
        options: [], // 选项个数
        img_url: '', // 封面图片
        anonymous: 1, // 匿名
        community_code: '', // 所属小区code
        end_time: '', // 结束时间
        start_time: '', // 开始时间
        multi: 1, // 是否支持
        remark: '', // 备注
        status: 1, // 状态
        title: ''// 投票标题
      }
    },
    // 点击增加选项
    addArray() {
      const obj = {
        description: '', // 选项描述
        img_url: '', // 图片内容 ，封面图片
        name: '', // 选项名称
        kd: '',
        limit: 1,
        img: []
      }
      // kd是做删除的时候用，options长度是多少，kd就是多少，正好对应下标index
      obj.kd = this.formData.options.length
      this.formData.options.push(obj)
    },
    // 图片
    // 移除区
    onRemove(result) {
      console.log(result)
      console.log(this.fileList.filter((item) => result.url !== item.url))
      this.fileList = this.fileList.filter((item) => result.url !== item.url)
      // 移除回显照片的同时也有移除上传照片中的数据
      if (this.formData.img_url instanceof Array) {
        // 是数组的话自己筛选删除
        const str = result.url.substring(26, 100)
        this.formData.img_url = this.formData.img_url.filter(item => item !== str)
      } else {
        // 点击提交的时候会把数组转字符串，如果提交失败，再点删除，就会走这个逻辑，然后重新转数组
        this.formData.img_url = this.formData.img_url.split(',')
        const str = result.url.substring(26, 100)
        this.formData.img_url = this.formData.img_url.filter(item => item !== str)
      }
    },
    // options移除图片
    handleRemove(index) {
      console.log(index)
      this.formData.options[index].img = []
    },
    // 上传之前
    beforeupload(file) {
      this.showPercent = true
    },
    // 上传成功触发
    onSuccess(result, fileList) {
      // console.log(result)
      this.fileList.push(fileList)
      this.showPercent = false
    },
    onSuccessFile(result, fileList) {
      // console.log(result)
      this.file.push(fileList)
      this.showPercent = false
    },
    // 手动上传
    async httpRequest(reslut) {
      const fd = new FormData()
      fd.append('file', reslut.file)
      const res = await getImgApi(fd)
      console.log(res)
      this.fileList.push({ url: `http://124.223.14.236:8881${res.data.data.url}` })
      // 因为提交失败转为字符串啦，这个时候添加用push会报错，所以判断一下
      if (this.formData.img_url instanceof Array) {
        this.formData.img_url.push(res.data.data.url)
      } else {
        console.log(333)
        // this.formData.img_url = this.formData.img_url.split(',')
        this.formData.img_url = [...this.formData.img_url]
        console.log(this.formData.img_url)
        this.formData.img_url.push(res.data.data.url)
      }
    },

    // 预览区
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 编辑器
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },

    handlePreview(file) {
      console.log(file)
    }
  }

}

</script>
<style src="@wangeditor/editor/dist/css/style.css">

</style>
<style scoped lang="scss">
::v-deep el-form-item__label{
    display: flex;
    flex-wrap: wrap;

}
   ::v-deep .el-form-item__label{
      width:100%;
      text-align: left;
    }
::v-deep .el-upload--picture-card{
  padding-top: 20px;
  width: 103px;
  height: 103px;
  line-height: 1;

}
::v-deep .el-form {
  height: 550px;
  overflow: scroll;
  overfLow-x:hidden
  }
.box{
   cursor:pointer;
  height: 38px;
  margin-top: 10px;
  text-align:center;
  line-height: 36px;
  border: 1px #007acc dashed;
}
.newly{
  height: 50px;
  width: 100%;
  line-height: 50px;
  padding-left: 40px;
  border-bottom: 1px solid red;
  margin-bottom: 20px;
  span{
    margin-right: 20px;
    cursor:pointer;
  }
}
::v-deep .updispck {
  .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
  .el-upload-list__item {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
}
::v-deep .el-table--scrollable-x .el-table__body-wrapper {
  // overflow-x: none;
  overflow: hidden;
}
::v-deep .disabled .el-upload--picture-card{
  display: none;
}
</style>
